<template>
  <div class="page-container">
    <el-card shadow="never">
      <!-- 搜索和操作区 -->
      <div style="margin-bottom: 20px; display: flex; justify-content: space-between;">
        <el-button type="primary" @click="refreshData">刷新列表</el-button>
      </div>

      <!-- 图片表格 -->
      <el-table :data="tableData" border stripe style="width: 100%" v-loading="loading">
        <el-table-column align="center" prop="imageName" label="图片名称" show-overflow-tooltip />
        <el-table-column align="center" label="预览">
          <template #default="{ row }">
            <img :src="getImageUrl(row)" style="width: fit-content; height: 40px; border-radius: 4px;"/>
          </template>
        </el-table-column>
        <el-table-column align="center" label="状态">
          <template #default="{ row }">
            <el-tag v-if="row.status === 'approved'" type="success">已通过</el-tag>
            <el-tag v-if="row.status === 'disabled'" type="info">已禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="createdAt" label="创建时间">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="上传用户ID">
          <template #default="{ row }">
            {{ row.userId || '-' }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template #default="{ row }">
            <el-button size="small" type="warning" @click="disableImage(row.id)" v-if="row.status === 'approved'">禁用</el-button>
            <span v-if="row.status !== 'approved'" style="color: #999;">已禁用</span>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div style="margin-top: 20px; text-align: right">
        <el-pagination
            background
            layout="total, prev, pager, next"
            :total="total"
            :page-size="pageSize"
            :current-page="currentPage"
            @current-change="handlePageChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import {nextTick, ref} from 'vue';
import request from '@/api/request';
import { ElMessage, ElMessageBox } from 'element-plus';
import Viewer from "viewerjs";
import "viewerjs/dist/viewer.css";

// 表格数据
const tableData = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const loading = ref(false);

// 获取图片列表
const fetchData = () => {
  loading.value = true;
  request.get('/api/image/list', {
    params: {
      pageNum: currentPage.value,
    }
  }).then(res => {
    const data = res.data.data;
    tableData.value = data.records;
    total.value = data.total;

    nextTick(() => {
      bindImgClick();
    });
  }).catch(() => {
    tableData.value = [];
    total.value = 0;
  }).finally(() => {
    loading.value = false;
  });
};

function preViewCover(elem) {
  const viewer = new Viewer(elem, {
    title: false,
    hide: () => {
      viewer.destroy();
    },
  });
  viewer.show();
}

function bindImgClick() {
  const elems = document.getElementsByClassName("page-container");
  for (let i = 0; i < elems.length; i++) {
    const imgList = elems[i].querySelectorAll("img");
    if (imgList.length > 0) {
      for (let j = 0; j < imgList.length; j++) {
        imgList[j].onclick = () => {
          preViewCover(elems[i]);
        };
      }
    }
  }
}

// 分页切换
const handlePageChange = (page) => {
  currentPage.value = page;
  fetchData();
};

// 刷新数据
const refreshData = () => {
  fetchData();
};

// 禁用图片
const disableImage = async (id) => {
  try {
    await ElMessageBox.confirm('确定要禁用这张图片吗？用户将无法查看。', '警告', {
      type: 'error',
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    });

    const res = await request.post(`/api/image/${id}/disable`);
    if (res.data.code === 200) {
      ElMessage.success('图片已禁用');
      fetchData(); // 刷新列表
    }
  } catch (error) {
    // 取消或请求失败
  }
};

// 获取图片URL
const getImageUrl = (row) => {
  return `/api/attachment/image/${row.imageName}`;
};

// 时间格式化
const formatDate = (isoStr) => {
  if (!isoStr) return '';
  return new Date(isoStr).toLocaleString('zh-CN', {
    year: 'numeric',
    month: 'short',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
};

// 初始化加载
fetchData();
</script>

<style scoped>
.page-container {
  padding: 20px;
}

img {
  cursor: pointer;
}
</style>
